package com.yuer;

import com.google.common.base.Charsets;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.Pipeline;
import us.codecraft.webmagic.processor.PageProcessor;

/**
 * 通用类
 */
public class ProcessorService implements PageProcessor {
    private Site site = Site.me().setRetryTimes(5).setSleepTime(1000)
            .setTimeOut(10000)
            .setCharset(Charsets.UTF_8.toString());

    private ProcessHandler processHandler;

    public ProcessorService(ProcessHandler processHandler) {
        this.processHandler = processHandler;
    }

    @Override
    public void process(Page page) {
        processHandler.process(page);
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void run(String fetchHome, ProcessHandler processHandler, Pipeline pipeline) {
        Spider.create(new ProcessorService(processHandler))
                .thread(Runtime.getRuntime().availableProcessors() * 10 * 5)
                .addUrl(fetchHome)
                .addPipeline(pipeline)
                .run();

    }
}
